<template>
  <div class="container">
    <NavBar :header-height="headerHeights" @doBack="doBack" title="选题详情"></NavBar>
    <div class="content" :style="{ height: contentHeight }" v-if="Object.entries(topicDetail).length !== 0">
      <div class="content-title">
        <div class="title">{{ topicDetail.title }}</div>
        <div class="bottom">
          <div class="hot" v-if="topicDetail.heat">
            <i class="hot-icon"></i>
            <span class="hot-num">&nbsp;{{ topicDetail.heat }}热度</span>
          </div>
          <div class="more">
            <span class="more-video">{{ topicDetail.videoTextNum }}视频文案&nbsp;|&nbsp;</span>
            <span class="more-poster">{{ topicDetail.pictorialNum }}海报模版</span>
          </div>
        </div>
      </div>
      <div class="abstract">
        <i class="icon"></i>
        <TextEllipsis :content="topicDetail.summary" single :rows="4" @clickExpand="clickExpand" expandText="查看全部">
          <span class="change-icon"></span>
        </TextEllipsis>
      </div>
      <div class="topic">
        <div class="topicItem" v-for="(item, index) in topicDetail.topicPointList" :key="index">
          <img class="symbol" src="../asset/icons/topic_symbol.png" />
          <div class="topicText">{{ item }}</div>
        </div>
      </div>
      <div class="divider"></div>
      <div class="video-paperwork">
        <div class="title">推荐视频文案</div>
        <div class="flex-wrap">
          <div class="content" v-if="topicDetail.videoTextList && topicDetail.videoTextList.length > 0">
            <div class="content-item" v-for="(item, index) in topicDetail.videoTextList" :key="index">
              <div class="video-container">
                <div class="text-container">
                  <span class="title">标题：</span>
                  <span class="text">{{ JSON.parse(item).title }}</span>
                </div>
                <div class="text-container">
                  <span class="title">正文：</span>
                  <span class="text">{{ JSON.parse(item).text }}</span>
                </div>
              </div>

              <span class="copy" id="copy" @click="handleCopy(item)">复制文案</span>
              <div class="btn flex-center" @click="goShot(item)">去拍摄</div>
            </div>
            <!-- <div class="content-default">
              <i class="default-icon"></i>
              <pre class="default-txt">{{ defaultText }}</pre>
              <div class="btn flex-center" @click="jumpToAiVideo(1)">使用AI创作</div>
            </div> -->
          </div>
        </div>
      </div>
      <div class="poster-template">
        <div class="title">推荐海报模版</div>
        <div class="scroll-wrap">
          <div class="pictorical-wrap" v-if="topicDetail.pictorialList && topicDetail.videoTextList.length > 0">
            <div class="pictorical-item" v-for="(item, index) in topicDetail.pictorialList" :key="index">
              <div @click="checkImage(item)" class="img-wrap">
                <img class="pictorical" :src="item.url" />
              </div>
              <div class="pictorical-bottom">
                <div class="keep-pictorical flex-center" @click="saveImage(index, item)">保存海报</div>
                <div class="change-template flex-center" @click="replaceTemplate(index, item)"><i class="refresh-icon"
                    :class="{ 'rotate-icon': rotating && currentIndex === index }"></i>换模版</div>
              </div>
            </div>
            <!-- <div class="default-pictorical">
              <div class="default-content">
                <i class="default-icon"></i>
                <div class="default-txt">{{ defaultText }}</div>
                <div class="btn flex-center" @click="jumpToAiVideo(2)">使用AI创作</div>
              </div>
            </div> -->
          </div>
        </div>
      </div>
    </div>
    <div class="shot-container" v-if="showPictorical" ref="imgRef">
      <img class="pictorical-shot" :src="pictoricalUrl" />
      <img class="water-mark" src="../asset/icons/ai_water_mark.png" />
    </div>
  </div>

  <Loading v-if="pageLoading"></Loading>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { debounce, getUrlParams } from "../utils";
import { headerHeight, getAccountInfos } from "@/../utils";
import { collectEvent, savePicture } from "@/../utils/bridge";
import { useRouter } from "vue-router";
import { reqSmartTopicDetail, reqReplaceTemplate, trainReplaceTemplate, reqReportEvent } from "../api";
import { jumpOpenImage } from "../api/bridge";
import { Toast } from "vant";
import Loading from "../components/Loading.vue";
import NavBar from "../components/NewNavbar.vue";
import TextEllipsis from "../components/TextEllipsis.vue";
const pageLoading = ref(false);
const topicId = ref();

const router = useRouter();

// 点击展开图标旋转
const clickExpand = () => {
  const arrowIconEl = document.querySelector(".change-icon");
  if (arrowIconEl.style.transform !== "rotate(180deg)") {
    arrowIconEl.style.transform = "rotate(180deg)";
  } else {
    arrowIconEl.style.transform = "rotate(0deg)";
  }
};

// 查看大图
const checkImage = (item) => {
  let urls = [];
  if (item.url) {
    console.log("item.url:" + item.url);
    urls.push(item.url);
    jumpOpenImage(urls);
  }
};

// 去拍摄
const goShot = (item) => {
  let videoDetail = JSON.parse(item);
  traceGoShoot(userId.value, topicId.value, videoDetail.id)
  console.log("去拍摄 标题:" + videoDetail.title + "，内容：" + videoDetail.text);
  window.location.href = `https://esales-local/ask_bob#visit?jumpUrl=aipage://1113?videoId=personalCreation&isNeedModify=false&title=${videoDetail.title}&screenPlay=${videoDetail.text}`;
};

// 去AI脚本创作
const benefitId = ref("210002");
const jumpToAiVideo = (type) => {
  let inputContent = "";
  let content = "";
  if (type === 1) {
    inputContent = topicDetail.value.videoPrompt;
    window.sessionStorage.setItem("CONTENTLIST", JSON.stringify(topicDetail.value.videoPromptContentList));
  } else {
    inputContent = topicDetail.value.pictorialPrompt;
    window.sessionStorage.setItem("CONTENTLIST", JSON.stringify(topicDetail.value.pictorialPromptContentList));
  }
  router.push(`./aiVideoScript?type=${type}&inputContent=${inputContent}&benefitId=${benefitId.value}`);
};

// 换模版
const rotating = ref(false);
const currentIndex = ref(-1);
let timer;
const imgRef = ref(); //保存海报
let showPictorical = ref(false);
let pictoricalUrl = ref();
//保存到相册
const saveImage = async (index, item) => {
  console.log(">>>> 保存海报 >>>>" + item.url);
  traceSavePoster(userId.value, topicId.value, item.id)
  pageLoading.value = true;
  showPictorical.value = true;
  pictoricalUrl.value = item.url;
  //pictoricalUrl.value = "https://stg.iobs.pingan.com.cn/download/lbdp-dip-dmz-stg/1ea6f980-069d-4dae-8f40-1a003412b49f.jpg"
  const onclone = (el) => { };
  console.log(">>>> 保存海报 >>>>" + imgRef.value);
  setTimeout(() => {
    savePicture(imgRef.value, {}, { onclone: onclone })
      .then((url) => {
        pageLoading.value = false;
        showPictorical.value = false;
        Toast("下载成功，可前往相册查看");
        console.log("保存报成功" + url);
      })
      .catch(() => {
        pageLoading.value = false;
        showPictorical.value = false;
        Toast("下载失败");
        console.log("保存报失败");
      });
  }, 100);
};

//更换模板
const replaceTemplate = async (index, item) => {
  traceChangeTemplate(userId.value, topicId.value, item.id)
  rotating.value = true;
  currentIndex.value = index;
  console.log(">>>> 更换模板 >>>>");
  const { code, data, msg } = await reqReplaceTemplate(userId.value, item.title, item.text);
  setTimeout(() => {
    rotating.value = false;
  }, 2000);
  if (code == 0 && data.result) {
    console.log(">>>> 接口数据 >>>>", data.result);
    let inferenceId = data.result.reqParams.id;
    //轮训查结果
    timer = setInterval(() => {
      trainingReplaceTemplate(index, inferenceId);
    }, 2000);
  } else {
    Toast("更换模板请求异常");
  }
};

const trainingReplaceTemplate = async (index, inferenceId) => {
  console.log(">>>> 轮训更换画报结果 >>>>");
  const { code, data, msg } = await trainReplaceTemplate(userId.value, inferenceId);
  if (code == 0 && data.result) {
    rotating.value = false;
    clearInterval(timer);
    console.log(">>>> 接口数据 >>>>", data.result.data);
    topicDetail.value.pictorialList[index].url = data.result.data.posterTemplateImg;
  } else if (code == 100000) {
    console.log(">>>> 处理中 >>>>");
  } else if (code == 100001 || code == 100002) {
    clearInterval(timer);
    Toast("更换模板轮训异常");
  }
};

//
const defaultText = ref("不满意推荐文本?\n让AI根据此话题帮你写文案!");

// 事件上报接口
const uploadEventTracking = async (contentId, eventType) => {
  let contentType = 1;
  if (eventType == 4 || eventType == 5) {
    contentType = 2;
  };
  const { code, msg } = await reqReportEvent(userId.value, topicId.value, contentType, contentId, eventType);
  if (code == 0) {
    console.log(">>>> 上报事件eventType >>>>", eventType);
  } else {
    Toast("上报事件接口异常" + msg);
  }
}

// 复制文案
const handleCopy = (item) => {
  let videoDetail = JSON.parse(item);
  traceCopyTextExposure(userId.value, topicId.value, videoDetail.id);
  console.log("复制文案 标题:" + videoDetail.title + "，内容：" + videoDetail.text);
  if (videoDetail.title || videoDetail.text) {
    let clipboard = new ClipboardJS("#copy", {
      text: () => {
        return videoDetail.title + "\n" + videoDetail.text; // 要复制的文本
      },
    });
    clipboard.on("success", () => {
      clipboard.destroy();
      Toast("复制成功！");
    });
    clipboard.on("error", () => {
      Toast("复制异常 请重试！");
      clipboard.destroy();
    });
  } else {
    Toast("暂无可复制文案！");
  }
};

// 定义头部及内容高度
const headerHeights = ref("44px");
if (headerHeight) {
  headerHeights.value = headerHeight();
}
const contentHeight = ref("100vh");
contentHeight.value = `calc(100vh - ${headerHeights.value})`;
const doBack = (preUrl) => {
  console.log(">>>> preUrl >>>>", preUrl);
  if (!preUrl) {
    history.back();
  } else {
    closeWindow();
  }
};

const topicDetail = ref({});
const getSmartTopicDetail = async () => {
  console.log(">>>> 请求话题详情数据 >>>>");
  const { code, data, msg } = await reqSmartTopicDetail(userId.value, topicId.value);
  if (code == 0 && data.result) {
    console.log(">>>> 接口数据 >>>>", data.result);
    topicDetail.value = data.result;
  } else {
    Toast("获取选题详情数据异常");
  }
};

// 挂载获取数据
const userId = ref("");
onMounted(async () => {
  topicId.value = getUrlParams("topicId");
  const { agentNo } = await getAccountInfos();
  userId.value = agentNo;
  pageLoading.value = true;
  await getSmartTopicDetail();
  pageLoading.value = false;
  traceTopicDetailExposure(userId.value);
});

</script>

<style lang="less" scoped>
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(720deg);
  }
}

.rotate-icon {
  animation: rotate 6s linear;
}

.container {
  background: #f7f7f7;

  .content {
    width: 100%;
    overflow: scroll;
    -webkit-overflow-scroll: touch;
    background: #f7f7f7;

    .content-title {
      padding: 15px;
      box-shadow: 0px 0.5px 0px 0px rgba(238, 238, 238, 1);

      .title {
        font-family: PingFangSC-Medium;
        font-size: 18px;
        color: #000000;
        font-weight: 500;
      }

      .double-ellipsis {
        max-height: 50px;
        line-height: 25px;
      }

      .bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;

        .hot {
          display: flex;

          .hot-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            background: url("../asset/icons/hot_16@2x.png") no-repeat;
            background-size: 100% 100%;
            margin-top: -1px;
          }

          .hot-num {
            opacity: 0.4;
            font-family: PingFangSC-Medium;
            font-size: 12px;
            color: #000000;
            letter-spacing: 0;
            line-height: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
          }
        }

        .more {
          opacity: 0.4;
          font-family: PingFangSC-Medium;
          font-size: 12px;
          color: #000000;
          letter-spacing: 0;
          text-align: right;
          line-height: 16px;
          font-weight: 500;
          display: flex;
          align-items: center;

          .more-icon {
            display: inline-block;
            margin-left: 5px;
            width: 16px;
            height: 16px;
            background: url("../asset/icons/load_more@2x.png") no-repeat;
            background-size: 100% 100%;
            transform: rotate(-90deg);
          }
        }
      }
    }

    .abstract {
      width: 345px;
      margin: 0 auto;
      margin-top: 15px;
      padding: 9px 10px 10px 10px;
      background: #ffffff;
      border-radius: 10px 10px 0px 0px;
      position: relative;

      .icon {
        display: inline-block;
        width: 18px;
        height: 18px;
        background: url("../asset/icons/yinhao@3x.png") no-repeat;
        background-size: 100%;
        position: absolute;
        top: -10px;
        left: -5px;
      }

      :deep(.text-ellipsis-content) {
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.8);
        letter-spacing: 0;
        text-align: justify;
        line-height: 1.5rem;
        font-weight: 400;
      }

      :deep(.text-ellipsis-action) {
        width: 325px;
        display: flex;
        justify-content: right;
        margin-left: 0px;
        margin-top: 5px;
        font-family: PingFangSC-Regular;
        font-size: 13px;
        letter-spacing: 0;
        text-align: right;
        line-height: 16px;
        font-weight: 400;
      }

      .change-icon {
        display: inline-block;
        width: 16px;
        height: 16px;
        background: url("../asset/icons/load_more@2x.png") no-repeat;
        background-size: 100% 100%;
        margin-left: 5px;
      }
    }

    .topic {
      width: 345px;
      margin: 0 auto;
      padding: 10px 10px 10px 10px;
      background: #f5f7fb;
      border-radius: 0px 0px 10px 10px;
      position: relative;
      box-shadow: 0px 2px 8px 0px rgba(216, 216, 216, 0.4);

      .topicItem {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        margin-top: 2px;

        .symbol {
          width: 14px;
          height: 16px;
        }

        .topicText {
          opacity: 0.8;
          font-family: PingFangSC-Regular;
          font-size: 13px;
          color: rgba(0, 0, 0, 0.8);
          letter-spacing: 0;
          font-weight: 400;
          overflow: hidden;
          text-overflow: ellipsis; //超出部分以省略号显示
          white-space: nowrap;
          line-height: 24px;
          margin-left: 5px;
        }
      }
    }

    .divider {
      width: 30px;
      height: 4px;
      background: #ff7744;
      margin-top: 10px;
      margin-left: 330px;
    }

    .video-paperwork {
      margin-left: 15px;
      margin-top: 15px;
      padding-right: 5px;

      .title {
        font-family: PingFangSC-Medium;
        font-size: 18px;
        color: #000000;
        font-weight: 500;
      }

      .flex-wrap {
        overflow-x: scroll;
        -ms-overflow-style: none;
        scrollbar-width: none;

        &::-webkit-scrollbar {
          display: none;
        }

        .content {
          display: flex;
          width: fit-content;
          overflow-x: scroll;

          .content-item {
            width: 325px;
            height: 183px;
            margin-top: 10px;
            overflow: auto;
            background: #ffffff;
            border-radius: 5px;
            margin-right: 10px;
            padding: 15px 10px 10px 15px;
            position: relative;

            .video-container {
              overflow-y: scroll;
              height: 126px;

              .text-container {
                padding: 0 5px;

                .title {
                  font-family: PingFangSC-Medium;
                  font-size: 15px;
                  color: #000000;
                  letter-spacing: 0;
                  font-weight: bold;
                  line-height: 20px;
                }

                .text {
                  font-family: PingFangSC-Regular;
                  font-size: 14px;
                  color: #000000;
                  letter-spacing: 0;
                  font-weight: 400;
                  line-height: 20px;
                }
              }
            }

            .copy {
              position: absolute;
              bottom: 12px;
              right: 97px;
              font-family: PingFangSC-Medium;
              font-size: 14px;
              color: #ff7744;
              line-height: 22px;
              font-weight: 500;
            }

            .btn {
              width: 72px;
              height: 30px;
              background: rgba(255, 119, 68, 0.1);
              border-radius: 18px;
              position: absolute;
              bottom: 8px;
              right: 10px;
              font-family: PingFangSC-Medium;
              font-size: 14px;
              color: #ff7744;
              line-height: 22px;
              font-weight: 500;
            }
          }

          .content-default {
            width: 325px;
            height: 183px;
            margin-top: 10px;
            background: url("../asset/img/default@2x.png") no-repeat;
            background-size: 100% 100%;
            border-radius: 5px;
            margin-right: 10px;
            display: flex;
            align-items: center;
            position: relative;

            .default-icon {
              display: inline-block;
              width: 72px;
              height: 72px;
              margin-left: 4px;
              background: url("../asset/icons/default_smart@2x.png") no-repeat;
              background-size: 100% 100% !important;
            }

            .default-txt {
              font-family: PingFangSC-Regular;
              font-size: 14px;
              color: #000000;
              letter-spacing: 0;
              font-weight: 400;
              line-height: 20px;
              margin-left: 10px;
            }

            .btn {
              width: 100px;
              height: 30px;
              background: rgba(255, 119, 68, 0.1);
              border-radius: 18px;
              position: absolute;
              bottom: 10px;
              right: 10px;
              font-family: PingFangSC-Medium;
              font-size: 14px;
              color: #ff7744;
              line-height: 22px;
              font-weight: 500;
            }
          }
        }
      }
    }

    .poster-template {
      margin-left: 15px;
      margin-top: 15px;
      padding-bottom: 50px;

      .title {
        font-family: PingFangSC-Medium;
        font-size: 18px;
        color: #000000;
        font-weight: 500;
      }

      .scroll-wrap {
        overflow-x: scroll;
        -ms-overflow-style: none;
        scrollbar-width: none;
        height: 275px; // 算了盒子阴影
        overflow-y: hidden;

        &::-webkit-scrollbar {
          display: none;
        }

        .pictorical-wrap {
          display: flex;
          width: fit-content;

          .pictorical-item {
            width: 168px;
            height: 224px;
            margin-top: 10px;
            position: relative;
            box-shadow: 0px 1px 3px 0px rgba(102, 102, 102, 0.05);
            border-radius: 8px 8px 0px 0px;
            margin-right: 10px;

            .default-pic {
              width: 69.36px;
              height: 41.34px;
              background: url("../asset/icons/default_pictorical@2x.png") no-repeat;
              background-size: 100% 100%;
              margin: 0 auto;
              margin-top: 91px;
            }

            .img-wrap {
              height: 224px;
              overflow: hidden;
            }

            .pictorical {
              width: 100%;
              height: 100%;
              object-fit: cover;
              object-position: top;
              display: block;
              border-radius: 8px 8px 0px 0px;
            }

            .multiple-icon {
              position: absolute;
              top: 8px;
              right: 8px;
              width: 24px;
              height: 24px;
              opacity: 0.6;
              background: rgba(0, 0, 0, 0.4);
              border: 0.5px solid rgba(255, 255, 255, 1);
              border-radius: 12px;

              .list-pic-icon {
                width: 16px;
                height: 16px;
                background: url("../asset/icons/list_pics@2x.png") no-repeat;
                background-size: 100% 100% !important;
              }
            }

            .pictorical-bottom {
              height: 36px;
              background: #ffffff;
              border-radius: 0px 0px 8px 8px;
              box-shadow: 0px 1px 2px 0.5px rgba(184, 174, 174, 0.15);
              display: flex;

              .keep-pictorical {
                width: 50%;
                font-family: PingFangSC-Medium;
                font-size: 13px;
                color: #ff7744;
                letter-spacing: 0;
                text-align: center;
                font-weight: 500;
                position: relative;

                &::after {
                  content: " ";
                  position: absolute;
                  right: 0;
                  background: #d6d3ca;
                  width: 1px;
                  height: 30px;
                  transform: scale(0.5);
                }
              }

              .change-template {
                width: 50%;
                opacity: 0.4;
                font-family: PingFangSC-Regular;
                font-size: 13px;
                color: #000000;
                letter-spacing: 0;
                text-align: center;
                font-weight: 400;

                .refresh-icon {
                  display: inline-block;
                  background: url("../asset/icons/icon_rotate@3x.png") no-repeat;
                  background-size: 100% 100%;
                  width: 16px;
                  height: 16px;
                  margin-right: 2px;
                }
              }
            }
          }
        }

        .default-pictorical {
          width: 168px;
          height: 260px;
          display: block;
          margin-top: 10px;
          margin-right: 10px;
          background-image: linear-gradient(180deg, #fffaed 0%, #fffaee 100%);
          border-radius: 8px;

          .default-content {
            width: 112px;
            height: 270px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            margin-left: 28px;

            .default-icon {
              display: inline-block;
              width: 72px;
              height: 72px;
              margin-left: 4px;
              background: url("../asset/icons/default_smart@2x.png") no-repeat;
              background-size: 100% 100% !important;
            }

            .default-txt {
              font-family: PingFangSC-Regular;
              font-size: 14px;
              color: #000000;
              letter-spacing: 0;
              font-weight: 400;
              line-height: 20px;
              text-align: center;
            }

            .btn {
              width: 100px;
              height: 30px;
              margin-top: 35px;
              background: rgba(255, 119, 68, 0.1);
              border-radius: 18px;
              font-family: PingFangSC-Medium;
              font-size: 14px;
              color: #ff7744;
              line-height: 22px;
              font-weight: 500;
            }
          }
        }
      }
    }
  }

  .shot-container {
    position: absolute;
    top: 0;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    width: 375px;
    z-index: -100;

    .pictorical-shot {
      width: 100%;
      height: auto;
    }

    .water-mark {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 164px;
      height: 27px;
    }
  }
}
</style>